<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="checkState">
        <el-select
          v-model="queryParams.checkState"
          placeholder="查看审核状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增、审核按钮 -->
    <el-row>
      <el-col :span="3">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <!-- 商品信息列表 -->
    <el-table v-loading="loading" :data="goodsList" tooltip-effect="light" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="商品名称" prop="goodsName" align="center" width="125" :show-overflow-tooltip="true"/>
      <el-table-column label="商品分类" prop="goodsClassify" align="center" width="125"/>
      <el-table-column label="商品库存" prop="goodsStock" align="center" width="125"/>
      <el-table-column label="商品价格" prop="goodsPrice" width="125px" align="center">
        <template slot-scope="scope">
          <el-tag type="danger">{{ scope.row.goodsPrice / '100' }}元</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品折扣" prop="goodsDiscount" width="125px" align="center">
        <template slot-scope="scope">
          <el-tag type="warning">{{ scope.row.goodsDiscount == '100' ? '无折扣' : scope.row.goodsDiscount / '10' + '折' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="checkState" align="center" width="125">
        <template slot-scope="scope">
          <el-tag :type="scope.row.checkState == '1' ? 'success'
               : scope.row.checkState == '0' ? 'info'
               : 'danger'" disable-transitions>
            {{ scope.row.checkState == '1' ? '审核通过' : scope.row.checkState == '0' ? '未审核' : '审核未通过' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            style="background:#3fc79e;color:white"
            icon="el-icon-search"
            v-if="scope.row.checkState !== '-1'"
            @click="handleLook(scope.row)"
          >查看
          </el-button>
          <el-button
            size="small"
            type="warning"
            icon="el-icon-edit"
            v-if="scope.row.checkState == '1'"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            v-if="scope.row.checkState == '1'"
            @click="handleDelete(scope.row.goodsId)"
          >删除
          </el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-tickets"
            v-if="scope.row.checkState == '-1'"
            @click="handleAdvice(scope.row)"
          >审核意见
          </el-button>
          <el-button
            size="small"
            style="background:#1FC5EE;color:white"
            icon="el-icon-edit-outline"
            v-if="scope.row.checkState == '-1'"
            @click="handleReadivce(scope.row)"
          >重新审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加和查看商品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="form.goodsName" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品品牌" prop="goodsBrand">
              <el-input v-model="form.goodsBrand" placeholder="请输入商品品牌"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品库存" prop="goodsStock">
              <el-input v-model.number="form.goodsStock" placeholder="请输入商品库存"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品分类" prop="goodsClassify">
              <el-select v-model="form.goodsClassify" style="width:100%" placeholder="请选择">
                <el-option
                  v-for="item in goodsOptions"
                  :key="item.classifyId"
                  :label="item.classifyName"
                  :value="item.classifyId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品价格" prop="goodsPrice">
              <el-input v-model="form.goodsPrice" placeholder="请输入商品价格"/>
              <el-tag v-if="form.goodsPrice == undefined" type="warning">单位：分</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品折扣" prop="goodsDiscount">
              <el-input v-model.number="form.goodsDiscount" placeholder="请输入商折扣"/>
              <el-tag v-if="form.goodsDiscount == undefined" type="warning">例：6折 输入60；0.6折 输入6；无折扣时输入100</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易地点" prop="dealPlace">
              <el-input v-model="form.dealPlace" placeholder="请输入交易地点"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="营业时间" prop="dealTime">
              <el-time-picker
                is-range
                v-model="form.dealTime"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品介绍" prop="goodsDescribe">
              <el-input v-model="form.goodsDescribe" :rows="4" type="textarea" placeholder="请在此输入商品介绍"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数说明" prop="goodsSku">
              <el-input v-model="form.goodsSku" :rows="4" type="textarea" placeholder="请在此输入商品参数"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品主图" prop="mainImgUrl">
              <el-upload
                ref='upload'
                action=""
                :http-request="uploadMainImg"
                list-type="picture-card"
                accept="image/*"
                :limit="1"
                :file-list="productImgs"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePictureCardPreview"
                :on-change="handleEdit"
                :on-remove="handleMainRemove"
                :class="{hide:hideUploadEdit}">
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <el-tag v-if="form.goodsName == undefined" type="warning">主图仅能上传1张</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="其他图片" prop="imgUrls">
              <el-upload
                ref='uploadOther'
                action=""
                :http-request="uploadOtherImg"
                list-type="picture-card"
                accept="image/*"
                :limit="5"
                :file-list="productOtherImgs"
                :before-upload="beforeAvatarUpload"
                :on-change="handleEditOther"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleOtherRemove"
                :class="{hide:hideUploadEditOther}">
                <i slot="default" class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
              <el-tag v-if="form.goodsName == undefined" type="warning">其他图片最多上传5张</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.goodsId == undefined" type="primary" @click="submitForm">提交审核</el-button>
        <el-button v-if="form.goodsId == undefined" @click="cancel">取 消</el-button>
        <el-button v-if="form.goodsId !== undefined" type="primary" @click="cancel">确 认</el-button>
      </div>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :title="title" :visible.sync="openAlter" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-col :span="12">
          <el-form-item label="商品库存" prop="goodsStock">
            <el-input v-model="form.goodsStock" placeholder="请输入商品库存"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品折扣" prop="goodsDiscount">
            <el-input v-model="form.goodsDiscount" placeholder="请输入商品折扣"/>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="submitGoods">保存修改</el-button>
      </div>
    </el-dialog>

    <!-- 审核意见 -->
    <el-dialog :title="title" :visible.sync="openAdvice" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="checkInfo">
              <el-input v-model="form.checkInfo" :rows="4" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="cancel">确 认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  reAuthGoods,
  authGoods,
  listGoods,
  getGoods,
  delGoods,
  addGoods,
  updateGoods,
  uploadImg,
  getClassify
} from '@/api/shop/goods'

export default {
  name: 'Goods',
  data() {
    var validateStock = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('库存不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数数值'))
        } else {
          if (value < 0 || value > 999) {
            callback(new Error('商品库存在0~999之间'))
          } else {
            callback()
          }
        }
      }, 500)
    }
    var validateDiscount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('无折扣请输入100'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数数值'))
        } else {
          if (value < 1 || value > 100) {
            callback(new Error('商品折扣在1~100之间'))
          } else {
            callback()
          }
        }
      }, 500)
    }
    return {
      // 上传图片
      dialogImageUrl: '',
      dialogVisible: false,
      productImgs: [], //用于图片回显
      productOtherImgs: [], //同上
      hideUploadEdit: false,
      hideUploadEditOther: false,
      imgUrlmap: new Map(),

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openAdvice: false,
      openAlter: false,
      openLook: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 商品列表
      goodsOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: undefined,
        checkState: undefined,
        createTimeBegin: undefined,
        createTimeEnd: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' },
          { min: 1, max: 200, message: "商品名称不能超过20个字", trigger: "blur" },
        ],
        goodsBrand: [
          { required: true, message: '商品品牌不能为空', trigger: 'blur' }
        ],
        goodsStock: [
          { required: true, validator: validateStock, trigger: 'blur' }
        ],
        goodsDiscount: [
          { required: true, validator: validateDiscount, trigger: 'blur' }
        ],
        goodsPrice: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' }
        ],
        dealPlace: [
          { required: true, message: '交易地点不能为空', trigger: 'blur' }
        ],
        goodsDescribe: [
          { required: true, message: '商品介绍不能为空', trigger: 'blur' }
        ],
        goodsSku: [
          { required: true, message: '参数说明不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    console.log('创建表单')
    this.getList()
    this.getDicts('shop_checkstate_status').then(response => {
      this.statusOptions = response.data
    })
    this.getClassify()
  },
  methods: {
    uploadMainImg(file) {
      uploadImg(file).then(res => {
        this.form.mainImgUrl = res.msg
      })
    },
    getClassify() {
      getClassify().then(response => {
        this.goodsOptions = response.data
      })
    },
    uploadOtherImg(file) {
      uploadImg(file).then(res => {
        this.imgUrlmap.set(file.file.uid, res.msg)
      })
    },
    //图片上传之前调用做一些拦截限制
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    // 图片大图预览
    handlePictureCardPreview(file) {
      this.dialogVisible = true
      this.dialogImageUrl = file.url
    },
    // 移除图片
    handleMainRemove(file, fileList) {
      let vm = this
      vm.hideUploadEdit = fileList.length >= 1
      this.form.mainImgUrl = undefined
    },
    // 移除其他图片
    handleOtherRemove(file, fileList) {
      this.imgUrlmap.delete(file.uid)
      let vm = this
      vm.hideUploadEditOther = fileList.length >= 5
    },
    //主图状态改变时
    handleEdit(file, fileList) {
      this.hideUploadEdit = fileList.length >= 1
    },
    //其他图片改变时
    handleEditOther(file, fileList) {
      this.hideUploadEditOther = fileList.length >= 5
    },

    /** 查询商品列表 */
    // addDateRange 方法在 main.js中全局挂载
    getList() {
      this.loading = true
      listGoods(this.addDateRange(this.queryParams)).then(
        response => {
          this.goodsList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.openAdvice = false
      this.openAlter = false
      this.openLook = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: undefined,
        goodsName: undefined,
        goodsBrand: undefined,
        goodsClassify: undefined,
        goodsPrice: undefined,
        goodsDiscount: undefined,
        goodsStock: undefined,
        dealPlace: undefined,
        mainImgUrl: undefined,
        goodsDescribe: undefined,
        goodsSku: undefined,
        imgUrls: [],
        dealTime: undefined,
        status: '',
        checkInfo: undefined
      }
      this.productImgs = []
      this.productOtherImgs = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      console.log(this.dateRange)
      this.queryParams.createTimeBegin = this.dateRange[0]
      this.queryParams.createTimeEnd = this.dateRange[1]
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.hideUploadEditOther = false
      this.hideUploadEdit = false
      this.productImgs = []
      this.productOtherImgs = []
      this.reset()
      this.open = true
      this.title = '添加商品'
    },
    /** 查看 */
    handleLook(row) {
      this.reset()
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        response.data.goodsClassify = parseInt(response.data.goodsClassify) //将select中回显的id转化为int型，因为后台返回的id是字符串
        this.form = response.data
        this.form.dealTime = this.form.dealTime.split('-')
        let img = { url: response.data.mainImgUrl }
        this.productImgs.push(img)
        let imgs = response.data.imgUrls
        console.log(imgs)
        if (imgs != undefined && imgs.length > 0) {
          imgs.filter((item, i) => {
            this.productOtherImgs.push({ url: item })
          })
        }
        this.hideUploadEditOther = true
        this.hideUploadEdit = true
        this.open = true
        this.title = '查看商品信息'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        this.form = response.data
        this.openAlter = true
        this.title = '修改商品信息'
      })
    },
    /** 查看审核意见 */
    handleAdvice(row) {
      console.log(row.checkInfo)
      this.form.checkInfo = row.checkInfo
      this.openAdvice = true
      this.title = '审核意见'
    },
    /** 重新提交审核意见 */
    handleReadivce(row) {
      let goodsInfo = {}
      goodsInfo.goodsId = row.goodsId
      this.$confirm('确认重新提交商品审核吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return reAuthGoods(goodsInfo)
      }).then(() => {
        this.msgSuccess('提交成功')
        this.getList()
      })
    },

    /** 提交审核按钮 */
    submitForm: function() {
      var val = this.form.dealTime
      this.form.dealTime = ''
      val.filter((item, i) => {
        this.form.dealTime += item
        if (i === 0) {
          this.form.dealTime += '-'
        }
      })
      this.form.imgUrls = Array.from(this.imgUrlmap.values())
      console.log(this.form)
      this.$refs['form'].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.goodsId != undefined) {
            updateGoods(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addGoods(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    //保存修改
    submitGoods: function() {
          if (this.form.goodsId != undefined) {
            updateGoods(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.openAlter = false
              this.getList()
            })
          }
    },

    /** 删除按钮操作 */
    handleDelete(goodsId) {
      const goodsIds = goodsId || this.ids;
      this.$confirm('是否确认删除该商品?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(goodsIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    }
  }
}
</script>
<style>
.hide .el-upload--picture-card {
  display: none;
}

.el-upload--picture-card {
  width: 120px;
  height: 120px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

.el-upload--picture-card i {
  font-size: 38px;
  color: #8c939d;
}
.el-tooltip__popper {
  font-size: 14px;
  width:300px;
}
</style>
